<?php
$user = $_GET['username'];
if(empty($user))
{
	throw new Exception("User Required");
}

require_once("global.php");

// Instantiate the API wrapper
$hdApi = new lastfmApi();

// Check the user is a valid last.fm user.
// Check by looking for weekly chart
// Store on success, exit on fail
$ifAuth = new lastfmApiAuth('setsession',array("apiKey"=>API_KEY));
$ifUser = $hdApi->getPackage($ifAuth, 'user');
$ifArtist = $hdApi->getPackage($ifAuth, 'artist');
$weekChartList = $ifUser->getWeeklyChartList(array('user'=>$user));
// TESTING:
// Limit number of charts to last 6 months
if (!is_array($weekChartList)) {
	$weekChartList = array();
}
$weekChartList = array_slice(array_reverse($weekChartList), 0, 25);

// Got the charts lists, take list get artists for each
// Index by "from" timestamp
$artistList = array();
$artistPercentage = array();
$tagPercentage = array();
$artistTags = array();

$totalPlayCount = array();
$artistPlayCount = array();
$tagCount = array();
$totalTagCount = array();

$startEndDates = array();

if (!file_exists(BASE_DIR.'/cache/'.$_GET['username'].'.xml')) {
	// Get the artists within each relevant chart
	foreach($weekChartList as $chartSpan)
	{
		$chartIndex = $chartSpan['from'];
		$artistList[$chartIndex] =
		$ifUser->getWeeklyArtistChart(array('user'=>$user,'from'=>$chartIndex, 'to'=>$chartSpan['to']));
		if (!is_array($artistList[$chartIndex])) {
			$artistList[$chartIndex] = array();
		}
		$artistList[$chartIndex] = array_slice($artistList[$chartIndex], 0, ARTIST_LIMIT);
		// Get the top 3 tags for the artist
		foreach($artistList[$chartIndex] as $artist)
		{
			$artistName = $artist['name'];
			// Get the tags for an artist
			$artistTags[$artistName] = $ifArtist->getTopTags(array('artist'=>$artistName));
			if (!is_array($artistTags[$artistName])) {
				$artistTags[$artistName] = array();
			}
			$artistTags[$artistName] = array_slice($artistTags[$artistName], 0, TAG_LIMIT);
			foreach($artistTags[$artistName] as $tag)
			{
				$tagCount[$chartIndex][$tag['name']]++;
				$totalTagCount[$chartIndex]++;
			}
			$artistPlayCount[$chartIndex][$artistName] = $artist['playcount'];
			$totalPlayCount[$chartIndex] += $artist['playcount'];
		}
		foreach($artistList[$chartIndex] as $artist)
		{
			$artistPercentage[$chartIndex][$artist['name']] =
			number_format(($artistPlayCount[$chartIndex][$artist['name']] /	$totalPlayCount[$chartIndex]) * 100, 2);
			foreach($artistTags[$artist['name']] as $tag)
			{
				$tagPercentage[$chartIndex][$tag['name']] +=
				($artistPercentage[$chartIndex][$artist['name']] / 100) * (100 / count($artistTags[$artist['name']]));
			}
		}
		$startEndDates[$chartIndex] = $chartSpan['to'];
	}
	require_once("classes/TasteTimeline.php");

	$data = TasteTimeline::staticGenerateChangesTimeline($tagPercentage);

	file_put_contents(BASE_DIR.'/cache/'.$_GET['username'].'.xml', TasteTimeline::staticGenerateXml($startEndDates, $data));
}
?>
